package com.wushijia.highconcurrency.threadpool;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import lombok.extern.log4j.Log4j;

/**
 * description:组合式异步编程：实现并发，充分利用cpu资源，实现程序最大吞吐量
 * <p>
 * 比较：1、Future比Thread更易用 2、
 *
 * @author yang
 * @date 2018/6/11 21:02
 */
@Log4j
public class FutureDemo {

  public static void main(String[] args) {
    //推荐手动创建线程池
    ExecutorService executorService = Executors.newCachedThreadPool();
    //以异步的方式在新的线程中执行耗时的操作
    Future<Double> future = executorService.submit(FutureDemo::doSomeLongComputation);
    //异步操作时做其他事情
    //doSomeThing();
    try {
      //如果操作完成，则返回结果，否则阻塞线程，直到结果返回，可设置阻塞超时时间，避免无止境的等待
      System.out.println(future.get(1L, TimeUnit.SECONDS));
    } catch (ExecutionException | InterruptedException | TimeoutException e) {
      log.error("线程" + Thread.currentThread().getName() + "执行失败", e);
    }
  }

  private static Double doSomeLongComputation() {
    System.out.println(1 / 0);
    return 11d;
  }
}
